<?php

namespace app\api\controller;

use app\api\model\Fake;
use app\api\model\User;
use app\api\validate\User as ValidateUser;
use app\BaseController;
use app\common\LogService;
use think\exception\ValidateException;

class Register extends BaseController
{
    public function index()
    {
        $param = input('post.');
        $config = getConfig('admin','sys_main');
        if ($config['reg_switch'] != 1) return error('当前App已关闭注册');
        $limit = User::where('reg_ip', getIP())->order('id desc')->find();
        if ($limit && date('d', time()) == date('d', $limit->getData('create_time'))) {
            return error('每天只能注册一个账号哦！');
        }

        $recordLog = function ($status, $message = '') {
            LogService::record(
                name: '用户注册',
                user_id: getUid(),
                status: $status,
                content: $message == '' ? [] : ['reason' => $message],
            );
        };
        try {
            validate(ValidateUser::class)->scene('register')->check($param);
            $user = User::where('qq', $param['qq']);
            if (!$user->findOrEmpty()->isEmpty()) {
                $recordLog(0, '已存在该QQ' . $param['qq']);
                return error('已存在该QQ，请更换其他的');
            }
            // 开启邀请码注册
            $needCode = $config['need_inviteCode'];
            if ($needCode == 1) {
                if (!isset($param['invite_code'])) {
                    $recordLog(0, '邀请码不能为空');
                    return error('邀请码不能为空');
                }
                $code = $param['invite_code'];
                if (!$this->verifyCode($code)) {
                    return error('邀请码不存在');
                }
            }
            $regConf = config('register');
            $data = [
                'qq' => $param['qq'],
                'nickname' =>   $regConf['nickname_prefix']. randStr($regConf['randNum']) . substr(time(), 5, 5),
                'password' => md5($param['password'] . config('secure.secure_salt')),
                'reg_ip' => getIP()
            ];
            $res = User::create($data);
            if ($res) {
                if ($needCode == 1) {
                    Fake::where(['fake' => $code])->update(['use_user_id' => $res->id]);
                }
                $recordLog(1);
                return success();
            }
            $recordLog(0);
            return error();
        } catch (ValidateException $e) {
            $recordLog(0, $e->getError());
            return error($e->getError(), 201);
        }
    }
    public function verifyCode($code)
    {
        $res = (new Fake())->useFake(fake: $code, specialType: 4);
        if ($res['code'] == 200) return true;
        return false;
    }
}
